/**
 * @author 李楠君
 * 短信查询
 */

package com.safe.ocs.services;

import java.util.List;

import net.sf.json.JSONObject;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.safe.ocs.beans.PageBean;
import com.safe.ocs.utils.HibernateUtil;

public class ViewMsg {
	
	/**
	 * 
	 * @param start  分页起始
	 * @param limit  每页记录数
	 * @param receiver  收信人号码
	 * @param status     发送状态
	 * @return
	 */
	public String findMessage(int start , int limit , String receiver , String status){
		String result = "";
		StringBuffer hqlWhere = new StringBuffer(" where 1=1");
		if(receiver!=null&&!"".equals(receiver)){
			hqlWhere.append(" and telNo=:telNo");
		}
		if(status!=null&&!"".equals(status)){
			hqlWhere.append(" and sendedStaut=:sendedStaut");
		}
		Session session = HibernateUtil.getSession();	
		Transaction tr = session.beginTransaction();
		try{
			String findHql ="select new OutputSMS(ID,telNo,msg,sendedStaut,remarks) from OutputSMS"+hqlWhere.toString();
		    Query query = session.createQuery(findHql);
		    if(receiver!=null&&!"".equals(receiver)){
				query.setParameter("telNo", receiver);
			}
			if(status!=null&&!"".equals(status)){
				query.setParameter("sendedStaut", new Boolean(status));
			}
			int totalProperty = query.list().size();
			List personList = query.setFirstResult(start).setMaxResults(limit).list();	
			PageBean bean = new PageBean(totalProperty,personList);
			result = JSONObject.fromObject(bean).toString();
			System.out.println(result.toString());
			tr.commit();
		}catch(Exception ex){
			tr.rollback();
		}finally{
			session.close();
		}		
		return result.toString();		
	}

}
